#ifndef PACKET_C_3e8a4e21_17f4_4d48_b54c_f5880c0704a6
#define PACKET_C_3e8a4e21_17f4_4d48_b54c_f5880c0704a6

/*
**
** Copyright (c) 2010 by Lorimark Solutions, LLC.
** All Rights Reserved.
** Send inquiries to: info@lorimarksolutions.com
**
*/

#include <evie-systems.h>
#include <packet.h>
#include <megaserial.h>
#include <serial.h>
#include <crc8.h>
#include <avr/eeprom.h>

#ifndef PACKET_DATA_SIZE
#error  PACKET.C: You must define PACKET_DATA_SIZE before including this file
#endif

packet_t packet;

/*
** This routine must be provided by the application.
**
*/
uint8 NodeIDMatch(void);

uint8 rxNetworkPacket(void)
{
  uint8  i;

  /*
  ** Get the attention character.  We can wait a bit for this.
  **
  */
  packet.atn = 0;
  while( (packet.atn != ':') && (rxUsartCount(0) > 0) )
  {
    crc8Result = 0;
    packet.atn = rxGet(0);
  }

  /*
  ** If we do not have an attention character, then
  **  just quit.
  **
  */
  if( packet.atn != ':' )
  {
//    printf( putc_lcd, "no atn  " );
    return(0);
  }

  /*
  ** Force read more bytes.
  **
  */
  packet.dst = rxGet(0);

  /*
  ** If the destination address is not for us
  **  then we can just quit.
  **
  */
  if( !NodeIDMatch() )
  {
    return(0);
  }


  /*
  ** Get the rest of the packet header.
  **
  */
  packet.src    = rxGet(0);
  packet.status = rxGet(0);
  packet.cmd    = rxGet(0);
  packet.len    = rxGet(0);

  /*
  ** If the packet length is too large then quit
  **
  */
  if( packet.len > PACKET_DATA_SIZE )
  {
    return(0);
  }

  /*
  ** Read each byte into the packet data section
  **
  */
  for( i=0; i<packet.len; i++ )
  {
    packet.dat[i] = rxGet(0);
  }

  /*
  ** Read the CRC byte.
  **
  */
  packet.dat[i] = rxGet(0);

  /*
  ** check the crc.  It should be zero
  **
  */
  if( crc8Result != 0 )
  {
    return(0);
  }

  /* * * * * * * * * * * * * * * * * * * * * * *
  ** At this point we have a valid packet and it
  **  is addressed to us.  We can now process the
  **  data in it and do whatever is requested.
  **
  */
  return(1);

}

#endif // #ifndef PACKET_C_3e8a4e21_17f4_4d48_b54c_f5880c0704a6

